//
//  RHPlantListViewController.m
//  RuiHeAppApp
//
//  Created by Jun on 2023/7/24.
//

#import "RHPlantListViewController.h"
#import "RHAddPlantViewController.h"
#import "RHPlantInfoViewController.h"
#import "RHMePlantMonitorVC.h"
#import "RHPlantListViewCell.h"
#import "RHPlantTransferVC.h"


@interface RHPlantListViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, assign) RequestType requestType;
//当前页数
@property (nonatomic, assign) NSInteger currentPage;
//总页数
@property (nonatomic, assign) NSInteger totalPage;
//每页多少条数据
@property (nonatomic, assign) NSInteger numOfPage;

@property (nonatomic ,copy) NSString *keyCode;
@end

@implementation RHPlantListViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear: animated];
    [self.navigationController setNavigationBarHidden:NO];
}

-(void)setPlantListArr:(NSMutableArray *)plantListArr
{
    _plantListArr = plantListArr;
    [self.tableView reloadData];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    _plantListArr = [NSMutableArray array];
    self.view.backgroundColor = CFTabViewBgColor;
    self.navigationItem.title = @"电站列表".rh_localized;
    self.requestType = RequestTypeRefresh;
    self.currentPage = 1;
    self.numOfPage = 20;
    [self setupUI];
    [self getPlantList];
}

- (void)setupUI{
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getAssetList) name:PlantListNeedUpdateNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getAssetList) name:PlantInfoDidChangeNotification object:nil];
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setBackgroundColor:UIColor.clearColor];
    [_tableView registerClass:[RHPlantListViewCell class] forCellReuseIdentifier:@"RHPlantListViewCell"];
    [self.view addSubview:_tableView];
    _tableView.ly_emptyView = [LYEmptyView emptyViewWithImageStr:@"nodata_icon_1" titleStr:@"没有数据".rh_localized detailStr:@""];
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
    }];
    kWeakSelf;
    [_tableView addHeaderRefresh:^{
        [weakSelf.tableView.mj_footer resetNoMoreData];
        weakSelf.requestType = RequestTypeRefresh;
        weakSelf.currentPage = 1;
        weakSelf.keyCode = @"";
        [weakSelf getPlantList];
        if(weakSelf.refreshBlock){
            weakSelf.refreshBlock();
        }
    }];
    
    [_tableView addBackFooterRefresh:^{
        weakSelf.requestType = RequestTypeAdd;
        weakSelf.currentPage++;
        [weakSelf getPlantList];
    }];
    
}

-(void)searchDeviceWithKeyCode:(NSString*)keyCode
{
    self.currentPage = 1;
    self.requestType = RequestTypeRefresh;
    [self.tableView endFooterResetNoMoreData];
    self.keyCode = keyCode;
    [self getPlantList];
}

#pragma mark ---------- 获取电站列表 -----------
-(void)getPlantList
{
    
    NSString *status = @"";
    if(self.index == 1){
        status = @"0";
    }else if(self.index == 2){
        status = @"1";
    }
    else if(self.index == 3){
        status = @"2";
    }
    
    [QMUITips showLoadingInView:self.view];
    
    //获取下级用户的电站列表
    if(self.userId>0){
        NSDictionary *para = @{@"pageNum":@(self.currentPage),
                               @"pageSize":@(self.numOfPage),
                               @"status":status,
                               @"userId":@(self.userId),
                               @"plantName":ValidNullData(self.keyCode)
                               
        };
        [RHPlantModel startGetWithCompletionAPIKey:H_getPlantListByUserId argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            if(resultModel.code == 200){
                NSInteger total = [request.responseObject[@"total"] integerValue];
                self.totalPage = total%self.numOfPage? total/self.numOfPage+1 : total/self.numOfPage;
                NSMutableArray *arr = [NSMutableArray arrayWithArray:resultModel.data];
                //下拉刷新
                if(self.requestType == RequestTypeRefresh){
                    [self.tableView endHeaderRefresh];
                    self.plantListArr = arr;
                }else{//上拉加载
                    [self.tableView endFooterRefresh];
                    [self.plantListArr addObjectsFromArray:arr];
                }
                if(self.currentPage >= self.totalPage){
                    [self.tableView endFooterRefreshWithNoMoreData];
                }
                [self.tableView reloadData];
                if(self.plantListArr.count == 0){
                    [self.tableView endFooterRefreshWithNoMoreData];
                }
            }

        } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            [QMUITips hideAllToastInView:self.view animated:YES];
            [self.tableView endHeaderRefresh];
        }];
        
    }else{
        //获取自己的电站列表
        NSDictionary *para = @{@"pageNum":@(self.currentPage),
                               @"pageSize":@(self.numOfPage),
                               @"status":status,
                               @"plantName":ValidNullData(self.keyCode)
        };
        [RHPlantModel startGetWithCompletionAPIKey:H_plantListByStatus argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            if(resultModel.code == 200){
                NSInteger total = [request.responseObject[@"total"] integerValue];
                self.totalPage = total%self.numOfPage? total/self.numOfPage+1 : total/self.numOfPage;
                NSMutableArray *arr = [NSMutableArray arrayWithArray:resultModel.data];
                //下拉刷新
                if(self.requestType == RequestTypeRefresh){
                    [self.tableView endHeaderRefresh];
                    self.plantListArr = arr;
                }else{//上拉加载
                    [self.tableView endFooterRefresh];
                    [self.plantListArr addObjectsFromArray:arr];
                }
                if(self.currentPage >= self.totalPage){
                    [self.tableView endFooterRefreshWithNoMoreData];
                }
                [self.tableView reloadData];
                if(self.plantListArr.count == 0){
                    [self.tableView endFooterRefreshWithNoMoreData];
                }
            }

        } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            [QMUITips hideAllToastInView:self.view animated:YES];
            [self.tableView endHeaderRefresh];
        }];
    }
    
    
}



#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.plantListArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    RHPlantListViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RHPlantListViewCell"];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    cell.model = self.plantListArr[indexPath.row];
    cell.idx = indexPath.row;
    kWeakSelf;
    
    MGSwipeButton *oneBtn = [MGSwipeButton buttonWithTitle:@"   " icon:[UIImage imageNamed:@"plant_delete"] backgroundColor:CFTabViewBgColor padding:15 callback:^BOOL(MGSwipeTableCell * _Nonnull cell) {
        QMUIAlertAction *action1 = [QMUIAlertAction actionWithTitle:@"取消".rh_localized style:QMUIAlertActionStyleCancel handler:NULL];
        QMUIAlertAction *action2 = [QMUIAlertAction actionWithTitle:@"确定".rh_localized style:QMUIAlertActionStyleDestructive handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
            [weakSelf deletePlantWithIndex:indexPath.row];
        }];
        QMUIAlertController *alertController = [QMUIAlertController alertControllerWithTitle:@"删除此电站?".rh_localized message:nil preferredStyle:QMUIAlertControllerStyleAlert];
        [alertController addAction:action1];
        [alertController addAction:action2];
        [alertController showWithAnimated:YES];
        
        return YES;
    }];
    //终端用户才有删除功能
    if([PrivateMange share].currentUser.hierarchyCode == UserRoleTypeTerminalUser){
        cell.rightButtons = @[oneBtn];
    }
    
    
    return cell;
}


#pragma mark ------- 删除电站 -------
-(void)deletePlantWithIndex:(NSInteger)index
{
    RHPlantModel *model = self.plantListArr[index];
    NSString *url = [NSString stringWithFormat:@"%@%ld",H_deletePlant,model.plant_id];
    [BaseModel startDeleteWithCompletionAPIKey:url argument:@{} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            [self.plantListArr removeObjectAtIndex:index];
            [self.tableView reloadData];
            [QMUITips showSucceed:@"成功".rh_localized];
            if (self.refreshBlock) {
                self.refreshBlock();
            }
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    RHPlantModel *model = self.plantListArr[indexPath.row];
    if(self.needAuth){
        if([model.authorization isEqualToString:@"1"]){
            RHPlantInfoViewController *vc = [[RHPlantInfoViewController alloc] init];
            vc.plantModel = model;
            [self.navigationController pushViewController:vc animated:YES];
        }else{
            [QMUITips showError:@"无权限查看".rh_localized];
        }
    }else{
//        RHPlantInfoViewController *vc = [[RHPlantInfoViewController alloc] init];
//        vc.plantModel = model;
//        [self.navigationController pushViewController:vc animated:YES];
        RHMePlantMonitorVC *vc = [[RHMePlantMonitorVC alloc] init];
        vc.plantModel = model;
        [self.navigationController pushViewController:vc animated:YES];
    }
    
}

#pragma mark - JXCategoryListContentViewDelegate
/**
 实现 <JXCategoryListContentViewDelegate> 协议方法，返回该视图控制器所拥有的「视图」
 */
- (UIView *)listView {
    return self.view;
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

@end
